package com.byzk.p2p.admin.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.system.dto.MemberLevel;
import com.byzk.p2p.admin.system.service.MemberService;
import com.byzk.p2p.admin.user.dto.InviteRef;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserService;
/**
 * 自动任务:每月1日0点根据投资人账户总额划分当月会员等级，划分后即生效
 * @author suker.zhou
 *
 */

@Component
public class ChangeLevelTask{
	
	@Autowired
	private UserService userService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private FundRecordService fundService;
	
	@Autowired
    private static Logger logger = Logger.getLogger(ChangeLevelTask.class); //日志服务
	
	/**
     * 定时器每月1日00:00:00更新系统中的用户等级
     * 测试用每小时执行一次
     */
	//@Scheduled(cron = "0 0 0 1 * ? ")
//	@Scheduled(cron = "0 0 21 * * ? ")
    public void taskCycle(){
    System.out.println("自动任务开始==============================开始时间："+DateUtils.getNowTimeString());
    logger.info("自动任务==============================开始时间："+DateUtils.getNowTimeString());
    /** 修改用户等级 **/

    Map<String, Object> queryMap = new HashMap<String, Object>();
    List<User> userList=userService.listAll1(queryMap);
    int i =0;
    String userName;
    double totalAmount;
    logger.info("记录数据总条数("+userList.size()+")");
    logger.info("============================开始执行修改用户等级=================================");
    for (User user : userList) {
    	userName = user.getUsername();
    	i++;
		UserAccount account=accountService.getByUserId(user.getId());
		if(account == null){
			logger.info("修改用户等级，正在处理第"+i+"条数据,未查询到用户["+userName+"]的账户数据!");
			continue;
		}
	    if(account.getLevel()==null){
	    	logger.info("修改用户等级，正在处理第"+i+"条数据,用户["+userName+"]没有评级积分等级!");
	    	continue;
	    }
	    totalAmount = account.getTotalAmount();
		MemberLevel level=memberService.getLevelByAmount(totalAmount);
		if(level==null || level.getId()==null){
		    logger.info("修改用户等级，正在处理第"+i+"条数据,用户["+userName+"]的资金总额为:["+totalAmount+"],未获取到对应的积分等级项!");
		    continue;
		}
		if(account.getLevel()==level.getId()){
			logger.info("修改用户等级，正在处理第"+i+"条数据,用户当前等级无需更改!");
			continue;
		}else{
			account.setLevel(level.getId());
			accountService.saveOrUpdate(account);
			logger.info("修改用户等级，第"+i+"笔记录更新成功!用户("+user.getRealname()+")的资金总额是["+totalAmount+"]，更新后等级是["+level.getName()+"]");
		}
    }
    
    /** 根据用户等级给邀请用户发放奖励，只给新平台新生成的下线发放奖励 **/
    int n=0;
    logger.info("============================开始执行给用户等级发放奖励==================================");
    queryMap = new HashMap<String, Object>();
    queryMap.put("oldUser", "N");
    userList = userService.listAll1(queryMap);
    logger.info("新平台新生产的用户记录总条数("+userList.size()+")");
    for(User user : userList) {
    	userName = user.getUsername();
    	n++;
    	if("N".equals(user.getFuionAccount())){
    		logger.info("给邀请用户发放奖励，正在处理第["+n+"]笔数据,该用户("+userName+")未开通托管账户。");
    		continue;
    	}
    	InviteRef inviteRef = null;
		try {
			inviteRef = userService.getInviteRefByUserId(user.getId());
		} catch (Exception e) {
			logger.info("给邀请用户发放奖励，正在处理第["+n+"]笔数据,该用户("+userName+")数据异常，原因："+e.getMessage());
			e.printStackTrace();
			continue;
		}
    	if(inviteRef == null) {//没有邀请关联用户
    		logger.info("给邀请用户发放奖励，正在处理第["+n+"]笔数据,当前用户("+userName+")没有上线!");
    		continue;
    	}
    	UserAccount account = accountService.getByUserId(user.getId());//用户账户
		if(account == null){
			logger.info("给邀请用户发放奖励，正在处理第["+n+"]笔数据,未查询到用户["+userName+"]的账户数据!");
			continue;
		} 

	    totalAmount = account.getTotalAmount();
		MemberLevel level = memberService.getById(account.getLevel());
		if(level == null){
			logger.info("给邀请用户发放奖励，正在处理第["+n+"]笔数据,用户["+userName+"]的资金总额为:["+totalAmount+"],未获取到对应的积分等级项!");
			continue;
		} 
		
		//添加奖励
		UserAccount parentAccount = accountService.getByUserId(inviteRef.getPid());//邀请用户账户
		if(parentAccount == null){
			logger.info("给邀请用户发放奖励，正在处理第["+n+"]笔数据,未获取到用户["+userName+"]的上线["+inviteRef.getPid()+"]的账户信息!");
			continue;
		}
		User parentUser = userService.getById(inviteRef.getPid());
		if(parentUser==null || "N".equals(parentUser.getFuionAccount())){
			logger.info("给邀请用户发放奖励，正在处理第["+n+"]笔数据,用户["+userName+"]的上线["+inviteRef.getPid()+"]没有开通富友托管!");
			continue;
		}
			
		/** 计算奖金收益,并判断是否领过等级奖励 **/
		Double amount = 0.00;
		if(account.getLevel()>inviteRef.getTakeAward()){
			for(int lv=inviteRef.getTakeAward()+1;lv<=account.getLevel();lv++){
				MemberLevel tempLevel=memberService.getById(lv);
				amount+=tempLevel.getRebate();
				fundService.addFundRecord(parentAccount.getUserId(), tempLevel.getRebate(), 0.0, "PC", "邀请"+user.getPhone()+"达到"+tempLevel.getName()+"返利", FundRecordType.Type.INVITE.index, 0.0);
				logger.info("给邀请用户发放奖励，第["+n+"]笔数据更新fund_record表成功!理论奖励金额income = "+tempLevel.getRebate());
			}
			
			amount = parentAccount.getStayAmount() < amount ? parentAccount.getStayAmount() : amount;
			String code = accountService.takeBonus(parentAccount.getUserId(), amount,"邀请"+user.getPhone()+"达到"+level.getName()+"待领变现");
			if("0000".equals(code)) {
				logger.info("给邀请用户发放奖励，第["+n+"]笔数据更新fund_record表成功!实际奖励金额income = "+amount);
				//更新关联用户信息,添加对应的等级奖励
				inviteRef.setTakeAward(account.getLevel());
				userService.updateInviteRef(inviteRef);
				logger.info("给邀请用户发放奖励，第["+n+"]笔数据更新invite_Ref表成功!");
			}
    	}
    }
	System.out.println("自动任务开始==============================结束时间："+DateUtils.getNowTimeString());
    logger.info("自动任务==============================结束时间："+DateUtils.getNowTimeString());			
    }
    
	 public static void main(String[] args) {
		 ChangeLevelTask task=new ChangeLevelTask();
		 task.taskCycle();
	}
}

